package cn.itsource.user.service.impl;

import cn.itsource.basic.exception.CustomException;
import cn.itsource.basic.util.AjaxResult;
import cn.itsource.basic.util.MD5Utils;
import cn.itsource.user.domain.LoginInfo;
import cn.itsource.user.mapper.LogininfoMapper;
import cn.itsource.user.service.ILoginInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginInfoServiceImpl implements ILoginInfoService {

    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public AjaxResult login(LoginInfo loginInfo) throws CustomException {
        //校验数据
        checkData(loginInfo);
        //根据用户名在数据库中查询对象数据
        LoginInfo info = logininfoMapper.loadByUsernameOrEmailOrPhoneAndType(loginInfo);
        if(info==null){
            throw new CustomException("用户不存在!!");
        }
        //比较密码，如果密码不相等，抛出异常
        if(!info.getPassword().equals
                (MD5Utils.encrypByMd5(loginInfo.getPassword()+info.getSalt()))){
            throw new CustomException("密码错误!!");
        }

        //随机产生的token，用于redis的key值
        String token = UUID.randomUUID().toString();

        //把登录信息放到redis
        redisTemplate.opsForValue().set(token, info, 30, TimeUnit.MINUTES);


        Map<String, Object> map = new HashMap<>();
        map.put("loginUser", info);
        map.put("token", token);
        //把token设置到返回结果集中
        return AjaxResult.me().setResultObject(map);
    }

    private void checkData(LoginInfo loginInfo) throws CustomException {
        if(StringUtils.isEmpty(loginInfo.getUsername())){
            throw new CustomException("用户名必填!!");
        }
        if(StringUtils.isEmpty(loginInfo.getPassword())){
            throw new CustomException("密码必填！！");
        }
        if(loginInfo.getType()==null){
            throw new CustomException("请完善资料!!");
        }
    }
}
